package com.campos.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.campos.collection.GPSService;
import com.campos.collection.GPSServiceWrapper;
import com.campos.collection.IMUSensor;
import com.campos.collection.LocationUtils;
import com.campos.collection.ProjectRW;
import com.campos.common.ContextData;
import com.campos.common.Config;
import com.campos.common.Registry;
import com.campos.process.DataCalib;

import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private static final String[] CAMERA_PERMISSION = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int CAMERA_REQUEST_CODE = 10;
    private int _PROJ_STATE = 0;
    protected Context selfContext = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selfContext = this;
        ProjectRW.instance = new ProjectRW();
        verifyStoragePermissions(this);
        Registry.getInstance().setApplicationContext(this);
        Button enableCamera = findViewById(R.id.enableCamera);
        enableCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enableCamera();
            }
        });
        findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(_PROJ_STATE == 0){
                    ProjectRW.instance.newpRroject();
                    initGPSLocation();
                    IMUSensor.instance.start(selfContext);

                    showToast("开始测量!");
                    Button btn = (Button)view;
                    if(btn !=null){
                        btn.setText("结束测量");
                    }
                    showIMUInfo();
                    _PROJ_STATE = 1;
                }else {
                    _PROJ_STATE = 0;

                    IMUSensor.instance.stop();
                    DataCalib dc = new DataCalib();
                    dc.calibrate();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        ProjectRW.instance.save();
                    }


                    showToast("结束测量!");
                    Button btn = (Button)view;
                    if(btn !=null){
                        btn.setText("开始测量");
                    }
                }
            }
        });

    }
    static final int REQUEST_IMAGE_CAPTURE = 1;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            {
                int permission = ActivityCompat.checkSelfPermission(activity,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
                }
            }
            {
                int permission = ActivityCompat.checkSelfPermission(activity,
                        Manifest.permission.CAMERA);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA},REQUEST_EXTERNAL_STORAGE);
                }
            }
            {
                int permission = ActivityCompat.checkSelfPermission(activity,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_EXTERNAL_STORAGE);
                }
            }
            {
                int permission = ActivityCompat.checkSelfPermission(activity,
                        Manifest.permission.ACCESS_COARSE_LOCATION);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},REQUEST_EXTERNAL_STORAGE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(
                this,
                CAMERA_PERMISSION,
                CAMERA_REQUEST_CODE
        );
    }

    private void enableCamera() {
        Intent intent = new Intent(this, CameraActivity.class);
        startActivity(intent);
    }
    public void initGPSLocation(){
        GPSServiceWrapper.getInstance().startService();
//        LocationUtils.addLocationListener(this, LocationManager.GPS_PROVIDER, new LocationUtils.ILocationListener() {
//            @Override
//            public void onSuccessLocation(Location location) {
//            }
//        });
    }
    private void showToast(final String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
    public float[] values, r;
    private double _lastTime = 0;

    private void showIMUInfo(){
//        values = new float[3];//用来保存最终的结果
//        r = new float[9];//
        IMUSensor.instance._callback = new IMUSensor.IMUSensorInfoCallback(){
            public void callback(IMUSensor.IMUSensorData sd){
                TextView tv = (TextView) findViewById(R.id.container);

                Date dt = new Date();
                Long timestamp = dt.getTime();
                if(timestamp - _lastTime < 500){
                    return;
                }
                _lastTime = timestamp;
                double azimuth = (sd.angles[0]);
                double pitch = (sd.angles[1]);
                double roll = (sd.angles[2]);
                double lon = -1;
                double lat = -1;
                double hei = -1;
                Location loc = GPSServiceWrapper.getInstance().getCurrentGPS();
                if(loc != null){
                    lon = loc.getLongitude();
                    lat = loc.getLatitude();
                    hei = loc.getAltitude();
                }
                tv.invalidate();
                tv.setText("Azimuth：" + azimuth + "\nPitch：" + pitch + "\nRoll：" + roll
                        +"\nLon:"+lon+"\nLat:"+lat+"\nHei:"+hei);
            }
        };
    }
}